<template>
  <div class="merchant-profile">
    <h2 class="page-title">店铺信息管理</h2>
    
    <el-card class="profile-card">
      <!-- 基本信息 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <div v-if="!editing" class="profile-view">
            <div class="header-section">
              <div class="logo-container">
                <img :src="merchantInfo.shopLogo || ''" class="shop-logo" alt="店铺Logo">
              </div>
              <div class="shop-title">
                <h3>{{ merchantInfo.shopName }}</h3>
                <div class="shop-rating">
                  <el-rate v-model="merchantInfo.rating" disabled show-score text-color="#ff9900"></el-rate>
                  <span class="shop-sales">月售 {{ merchantInfo.monthlySales }} 单</span>
                </div>
                <div class="shop-status">
                  <el-tag :type="merchantInfo.status === 1 ? 'success' : merchantInfo.status === 0 ? 'warning' : 'danger'">
                    {{ getStatusText(merchantInfo.status) }}
                  </el-tag>
                  <el-tag :type="merchantInfo.businessStatus === 1 ? 'success' : 'info'" style="margin-left: 10px;">
                    {{ merchantInfo.businessStatus === 1 ? '营业中' : '休息中' }}
                  </el-tag>
                </div>
              </div>
              <div class="action-buttons">
                <el-button type="primary" icon="el-icon-edit" @click="startEditing">编辑信息</el-button>
              </div>
            </div>
            
            <el-divider></el-divider>
            
            <div class="info-section">
              <div class="info-row">
                <div class="info-label">店铺描述</div>
                <div class="info-value">{{ merchantInfo.shopDesc || '暂无描述' }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">营业时间</div>
                <div class="info-value">{{ merchantInfo.businessHours || '暂未设置' }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">联系人</div>
                <div class="info-value">{{ merchantInfo.contactPerson }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">联系电话</div>
                <div class="info-value">{{ merchantInfo.contactPhone }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">店铺地址</div>
                <div class="info-value">{{ merchantInfo.shopAddress }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">创建时间</div>
                <div class="info-value">{{ merchantInfo.createTime }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">更新时间</div>
                <div class="info-value">{{ merchantInfo.updateTime }}</div>
              </div>
            </div>
          </div>
          
          <div v-else class="profile-edit">
            <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
              <el-form-item label="店铺名称" prop="shopName">
                <el-input v-model="editForm.shopName" placeholder="请输入店铺名称"></el-input>
              </el-form-item>
              
              <el-form-item label="店铺Logo" prop="shopLogo">
                <el-upload
                  class="avatar-uploader"
                  :action="`${$baseURL}/api/upload/merchant`"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :before-upload="beforeLogoUpload">
                  <img v-if="editForm.shopLogo" :src="editForm.shopLogo" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <div class="el-upload__tip" slot="tip">只能上传JPG/PNG文件，且不超过2MB</div>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="店铺描述" prop="shopDesc">
                <el-input type="textarea" v-model="editForm.shopDesc" :rows="3" placeholder="请输入店铺描述"></el-input>
              </el-form-item>
              
              <el-form-item label="营业时间" prop="businessHours">
                <el-input v-model="editForm.businessHours" placeholder="例如：10:00-22:00"></el-input>
              </el-form-item>
              
              <el-form-item label="联系人" prop="contactPerson">
                <el-input v-model="editForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
              </el-form-item>
              
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话"></el-input>
              </el-form-item>
              
              <el-form-item label="店铺地址" prop="shopAddress">
                <el-input v-model="editForm.shopAddress" placeholder="请输入店铺地址"></el-input>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="submitForm">保存</el-button>
                <el-button @click="cancelEditing">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="营业资质" name="license">
          <div class="license-section">
            <div class="license-item">
              <h4>营业执照</h4>
              <div class="license-image">
                <img :src="merchantInfo.businessLicense" alt="营业执照" @click="showImagePreview(merchantInfo.businessLicense)">
              </div>
              <div class="upload-btn" v-if="editing">
                <el-upload
                  :action="`${$baseURL}/api/upload/merchant`"
                  :show-file-list="false"
                  :on-success="handleBusinessLicenseSuccess"
                  :before-upload="beforeLicenseUpload">
                  <el-button size="small" type="primary">更新营业执照</el-button>
                </el-upload>
              </div>
            </div>
            
            <div class="license-item">
              <h4>食品经营许可证</h4>
              <div class="license-image">
                <img :src="merchantInfo.foodLicense" alt="食品经营许可证" @click="showImagePreview(merchantInfo.foodLicense)">
              </div>
              <div class="upload-btn" v-if="editing">
                <el-upload
                  :action="`${$baseURL}/api/upload/merchant`"
                  :show-file-list="false"
                  :on-success="handleFoodLicenseSuccess"
                  :before-upload="beforeLicenseUpload">
                  <el-button size="small" type="primary">更新食品经营许可证</el-button>
                </el-upload>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewVisible" title="图片预览" width="50%">
      <img :src="previewImage" alt="预览图片" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'MerchantProfile',
  data() {
    return {
      // 当前标签页
      activeTab: 'basic',
      
      // 是否编辑模式
      editing: false,
      
      // 商家信息
      merchantInfo: {
        id: null,
        userId: null,
        shopName: '',
        shopLogo: '',
        shopDesc: '',
        businessHours: '',
        contactPerson: '',
        contactPhone: '',
        shopAddress: '',
        businessLicense: '',
        foodLicense: '',
        status: 0,
        businessStatus: 0,
        rating: 0,
        monthlySales: 0,
        createTime: '',
        updateTime: ''
      },
      
      // 编辑表单
      editForm: {
        shopName: '',
        shopLogo: '',
        shopDesc: '',
        businessHours: '',
        contactPerson: '',
        contactPhone: '',
        shopAddress: '',
        businessLicense: '',
        foodLicense: ''
      },
      
      // 表单校验规则
      rules: {
        shopName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        shopAddress: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ]
      },
      
      // 图片预览
      previewVisible: false,
      previewImage: ''
    }
  },
  created() {
    this.getMerchantInfo()
  },
  methods: {
    // 获取商家信息
    getMerchantInfo() {
      const userId = this.$store.state.user.id
      axios.get(`/api/merchants/user/${userId}`)
        .then(response => {
          if (response.code === 200) {
            this.merchantInfo = response.data
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 开始编辑
    startEditing() {
      this.editForm = {
        shopName: this.merchantInfo.shopName,
        shopLogo: this.merchantInfo.shopLogo,
        shopDesc: this.merchantInfo.shopDesc,
        businessHours: this.merchantInfo.businessHours,
        contactPerson: this.merchantInfo.contactPerson,
        contactPhone: this.merchantInfo.contactPhone,
        shopAddress: this.merchantInfo.shopAddress,
        businessLicense: this.merchantInfo.businessLicense,
        foodLicense: this.merchantInfo.foodLicense
      }
      this.editing = true
    },
    
    // 取消编辑
    cancelEditing() {
      this.editing = false
    },
    
    // 提交表单
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          axios.put(`/api/merchants/${this.merchantInfo.id}`, this.editForm)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('店铺信息更新成功')
                this.editing = false
                this.getMerchantInfo() // 刷新数据
              } else {
                this.$message.error(response.message || '更新失败')
              }
            })
            .catch(error => {
              console.error('更新店铺信息失败', error)
              this.$message.error('更新店铺信息失败')
            })
        } else {
          return false
        }
      })
    },
    
    // Logo上传成功处理
    handleLogoSuccess(response, file) {
      if (response.code === 200) {
        this.editForm.shopLogo = response.data.fileUrl
        this.$message.success('Logo上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    
    // Logo上传前校验
    beforeLogoUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        this.$message.error('上传Logo只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传Logo大小不能超过 2MB!')
      }
      
      return isJPG && isLt2M
    },
    
    // 显示图片预览
    showImagePreview(url) {
      this.previewImage = url
      this.previewVisible = true
    },
    
    // 证件上传前校验
    beforeLicenseUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!')
      }
      
      return isImage && isLt5M
    },
    
    // 营业执照上传成功处理
    handleBusinessLicenseSuccess(response, file) {
      if (response.code === 200) {
        this.editForm.businessLicense = response.data.fileUrl
        this.$message.success('营业执照上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    
    // 食品经营许可证上传成功处理
    handleFoodLicenseSuccess(response, file) {
      if (response.code === 200) {
        this.editForm.foodLicense = response.data.fileUrl
        this.$message.success('食品经营许可证上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const texts = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      }
      return texts[status] || '未知状态'
    }
  }
}
</script>

<style scoped>
.merchant-profile {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.profile-card {
  margin-bottom: 20px;
}

.header-section {
  display: flex;
  margin-bottom: 20px;
}

.logo-container {
  width: 100px;
  height: 100px;
  margin-right: 20px;
}

.shop-logo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.shop-title {
  flex: 1;
}

.shop-title h3 {
  margin: 0 0 10px;
  font-size: 20px;
}

.shop-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.shop-sales {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

.action-buttons {
  align-self: flex-start;
}

.info-section {
  margin-top: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-label {
  width: 120px;
  font-weight: bold;
  color: #606266;
}

.info-value {
  flex: 1;
  color: #303133;
}

.license-section {
  display: flex;
  flex-wrap: wrap;
}

.license-item {
  width: 50%;
  padding: 0 20px 20px 0;
  box-sizing: border-box;
}

.license-item h4 {
  margin: 0 0 10px;
  font-size: 16px;
}

.license-image img {
  width: 100%;
  max-width: 300px;
  height: auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-btn {
  margin-top: 10px;
}
</style> 